//智能设置

function firstInit(proxySettings){
	//todo
	intelligentModeSettings.init = true;
    downloadRule();
    setIntelligentProxy(proxySettings);
}
//重设智能设置
function resetIntelligentModeSettings(){
    //清除智能设置
    await chrome.storage.local.clear("intelligentModeSettings");
    location.reload(true);
}
//下载并更新规则并保存
function downloadRule(){
	console.debug("function downloadRule start");
    //选择需要下载的规则
	var directL = [];
	var proxyL = [];
	var blockL = [];
	if (directListFile_isEnable) {
		directL.push(intelligentModeSettings.directListFile);
	};
	if(proxyListFile_isEnable){
		proxyL.push(intelligentModeSettings.proxyListFile);
	};
	if (adListFile_isEnable) {
		blockL.push(intelligentModeSettings.adListFile);
	};
	if (chinaListFile_isEnable) {
		directL.push(intelligentModeSettings.chinaListFile);
	};
	if (appleCNListFile_isEnable) {
		directL.push(intelligentModeSettings.appleCNListFile);
	};
	if (googleCNListFile_isEnable) {
		directL.push(intelligentModeSettings.googleCNListFile);
	};
	if (gfwListFile_isEnable) {
		proxyL.push(intelligentModeSettings.gfwListFile);
	};
	//下载规则
	//直连列表
	var directList = [];
    //导入默认规则
	directList.push(intelligentModeSettings.intelligent_mode_default_bypass_list);
	directL.forEach((url)=>{
		directList.push(readTXT(url));
	});
	//代理列表
	var proxyList =[];
	proxyL.forEach((url)=>{
		proxyList.push(readTXT(url));
	});
	//拒否列表
	var blockList =[];
	blockL.forEach((url)=>{
		blockList.push(readTXT(url));
	});
	//去重
	var directListUniqueArray = Array.from(new Set(directList));
	var proxyListUniqueArray = Array.from(new Set(proxyList));
	var blockListUniqueArray = Array.from(new Set(blockList));
    //封装规则
	intelligentModeSettings.intelligent_mode_direct_list = intelligentBuildList(directListUniqueArray,"DIRECT",null,null);
	intelligentModeSettings.intelligent_mode_proxy_list = intelligentBuildList(
		proxyListUniqueArray,
		intelligentModeSettings.proxySetting.scheme,
		intelligentModeSettings.proxySetting.host,
		intelligentModeSettings.proxySetting.port
	);
    intelligentModeSettings.intelligent_mode_block_list = intelligentBuildList(blockListUniqueArray,"BLOCK",null,null);
    //写入mainList
	intelligentModeSettings.mainList.push(intelligentModeSettings.intelligent_mode_direct_list);
	intelligentModeSettings.mainList.push(intelligentModeSettings.intelligent_mode_proxy_list);
	intelligentModeSettings.mainList.push(intelligentModeSettings.intelligent_mode_block_list);
	//利用mainList构建Pac脚本
	intelligentModeSettings.pacScript = buildPacScript(mainList);
    //保存direct_list, proxy_list, block_list,mainList,pacScript
    chrome.storage.local.set({"intelligentModeSettings":intelligentModeSettings});
	console.debug("function downloadRule end , intelligentModeSettings = ",intelligentModeSettings);
}
//保存智能代理的代理服务器
function setIntelligentProxy(proxySettings){
    console.debug("function setIntelligentProxy start");
	//获取智能代理的代理服务器
    intelligentModeSettings.proxySetting.scheme = proxySettings.scheme;
    intelligentModeSettings.proxySetting.host = proxySettings.host;
    intelligentModeSettings.proxySetting.port = proxySettings.port;
    chrome.storage.local.set({"intelligentModeSettings":intelligentModeSettings});
    console.debug("function setIntelligentProxy end");
}


//入口函数
//智能判断是否是第一次设置,如果是第一次设置,则进行初始化
//否则,进行手动设置
function getIntelligentProxySetting(proxySettings,callback){
    console.debug("function getIntelligentProxySetting start");
    if(intelligentModeSettings.init){
		//已经初始化过
		chrome.storage.local.get("intelligentModeSettings",(result)=>{
			console.debug("getIntelligentProxySetting result = ", result);
		    intelligentModeSettings = result.intelligentModeSettings;
		});
	} else {
	    //初始化
		intelligentModeSettings.init = true;
		firstInit(proxySettings);
	}
	//启用脚本设置
	pacScriptProxy(intelligentModeSettings.pacScript,callback);
    console.debug("function getIntelligentProxySetting end");
}
//从网络获取最新列表
function readTXT(txtUrl){
	console.debug("function readTXT start");
	fetch(txtUrl)
	.then(response => {
		if (!response.ok) {
			throw new Error('Network response was not ok ' + response.statusText);
		}
		return null;
	})
	.then(data => {
		console.debug("function readTXT end, UrlList = ",data);
		return splitStringByDelimiter(data);
	})
	.catch(error => {
		console.error('There has been a problem with your fetch operation:', error);
	});
}

//构建列表
function intelligentBuildList(url_list,scheme,proxyHost,proxyPort){
	var proxList = [];
	url_list.forEach((url)=>{
		var prox = {
			url : url,
			type : scheme,
			address : proxyHost,
			port : proxyPort
		};
		proxList.push(prox);
	});
	return proxList;
}

/**
 * proxyList是一个list
 * proxyList的元素是一个Object
 * prox = {
 * 	url: "目标地址",
 * 	type: "代理服务器本身所使用的协议",
 * 	address: "代理地址",
 * 	port: "代理端口"
 * }
 * 
 * @returns {String proxyFile}
 */
//构建pac函数
function buildPacScript(proxyList) {
	console.debug("function buildPacScript start");

	var pacScript = "function FindProxyForURL(url, host) {\n";
	proxyList.forEach((prox) => {
		pacScript += buildPacScriptBody(prox.host,prox.type,prox.address,prox.port);
	});
	pacScript += "	return 'DIRECT';\n";
    pacScript += "}\n";

	console.debug("function pacScript end , pacScript = ", pacScript );
	return pacScript;
}
function buildPacScriptBody(host,type,address,port){
	console.debug("function buildPacScriptBody start");
	var pacScript = "";
	if (host.startsWith("regexp:")) {
		host = host.substring("regexp:".length);
		pacScript += "	if (new RegExp('" + host + "').test(host)) {\n";
		if (type == "DIRECT" || type == "SYSTEM" || type == "BLOCK") {
			pacScript += "		return '"+type+"';\n";
		} else {
			pacScript += "		return '"+type+" " + address + ":" + port + "'; DIRECT ;\n";
		}
		pacScript += "	}\n";

	} else if (host.startsWith("full:")) {
		host = host.substring("full:".length);
		
		pacScript += "	if ('"+host+"' == host) {\n";
		if (type == "DIRECT" || type == "SYSTEM" || type == "BLOCK") {
			pacScript += "		return '"+type+"';\n";
		} else {
			pacScript += "		return '"+type+" " + address + ":" + port + "'; DIRECT ;\n";
		}
		pacScript += "	}\n";
	} else {
		pacScript += "	if(shExpMatch(host, '" + host + "')){\n";
		if (type == "DIRECT" || type == "SYSTEM" || type == "BLOCK") {
			pacScript += "	return '"+type+"';\n";
		} else {
			pacScript += "	return '"+type+" " + address + ":" + port + "'; DIRECT ;\n";
		}
		pacScript += "	}\n";
	}
	console.debug("function buildPacScriptBody end , buildPacScriptBody = ", pacScript );
	return pacScript;
}